﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace ForexService
{
    public class ForexNewsParser 
    {
        string url1 = "http://www.forexfactory.com/calendar.php";
        string url2 = "http://www.forexpeacearmy.com/forex_news_calendar/index.php";

        List<string> times = new List<string>();
        List<string> messages = new List<string>();

        List<ForexNews> newsList = new List<ForexNews>();

        public List<ForexNews> NewsList
        {
            get { return newsList; }
            set { newsList = value; }
        }

        string StripTags(string source)
        {
            char[] array = new char[source.Length];
            int arrayIndex = 0;
            bool inside = false;

            for (int i = 0; i < source.Length; i++)
            {
                char let = source[i];
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (!inside)
                {
                    array[arrayIndex] = let;
                    arrayIndex++;
                }
            }
            return new string(array, 0, arrayIndex);
        }

        string[] GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
        {
            string[] result = { "", "" };
            int iIndexOfBegin = strSource.IndexOf(strBegin);

            if (iIndexOfBegin != -1)
            {
                if (includeBegin)
                {
                    iIndexOfBegin -= strBegin.Length;
                }

                strSource = strSource.Substring(iIndexOfBegin + strBegin.Length);
                int iEnd = strSource.IndexOf(strEnd);

                if (iEnd == -1)
                {
                    iEnd = strSource.IndexOf("table");

                }

                if (iEnd != -1)
                {
                    if (includeEnd)
                    {
                        iEnd += strEnd.Length;
                    }
                    result[0] = strSource.Substring(0, iEnd);

                    if (iEnd + strEnd.Length < strSource.Length)
                    {
                        result[1] = strSource.Substring(iEnd + strEnd.Length);
                    }
                }

            }
            else
            {
                result[1] = strSource;
            }
            return result;
        }

        string GetDate(int day, bool first)
        {
            DateTime time;
            string format;

            if (first)
            {
                format = "MMM d";
            }
            else
            {
                format = "d MMM";
            }

            if (day == 0)
            {
                time = DateTime.Now;
            }
            else
            {
                time = DateTime.Now.AddDays((double)day);
            }
            return time.ToString(format);
        }

      
        public void ParseNewsData()
        {
            times.Clear();
            messages.Clear();

            try
            {
                using (WebClient wc1 = new WebClient())
                {
                    byte[] dataBuffer = wc1.DownloadData(url1);
                    string download = Encoding.ASCII.GetString(dataBuffer);

                    string today = GetDate(0, true);
                    string tomorrow = GetDate(1, true);

                    string[] rez = GetStringInBetween(today, tomorrow, download, true, true);

                    foreach (Match matchTime in Regex.Matches(rez[0], @"\t\t\t<span class=""smallfont"">(.*)\</span>"))
                    {
                        string time = matchTime.Groups[1].Value;

                        if (time.Length > 10)
                        {
                            time = StripTags(time);
                        }
                        times.Add(time);
                    }

                    foreach (Match matchMessage in Regex.Matches(rez[0], @" style=""padding-left: 11px;"">(.*)</div>"))
                    {
                        messages.Add(matchMessage.Groups[1].Value);
                    }

                    if (times.Count() < 1)
                    {
                        // no data found, load from second
                        LoadDataFromSecondServer();
                    }
                    else
                    {
                        ComposeForexNewsList();
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Client1: " + ex.Message);
                LoadDataFromSecondServer(); // look on second site
            }
        }

        List<ForexNews> ComposeForexNewsList()
        {
            newsList.Clear();

            if (times.Count > 0)
            {
                for (int i = 0; i < times.Count; i++)
                {
                    newsList.Add(new ForexNews(Convert.ToString(times[i]), Convert.ToString(messages[i])));
                }
            }

            return newsList;
        }

        void LoadDataFromSecondServer()
        {
            try
            {
                using (WebClient wc2 = new WebClient())
                {
                    byte[] dataBuffer = wc2.DownloadData(url2);
                    string download = Encoding.ASCII.GetString(dataBuffer);

                    string today = ", " + GetDate(0, false);
                    string tomorrow = ", " + GetDate(1, false);

                    string[] ret = GetStringInBetween(today, tomorrow, download, true, true);

                    foreach (Match matchTime in Regex.Matches(ret[0], @"<td class='alt1'>(.*)</td><td class='alt2'><table cellspacing=""0"" cellpading=""0"" border=""0"" width=""100%"">"))
                    {
                        times.Add(matchTime.Groups[1].Value);
                    }

                    foreach (Match matchMessage in Regex.Matches(ret[0], @"</td></tr></table></td><td class='alt1' align='left'>(.*)</td><td class='alt2'><table cellpadding='0'"))
                    {
                        messages.Add(matchMessage.Groups[1].Value);
                    }

                    ComposeForexNewsList();
                }
            }
            catch (Exception ex2)
            {
                //MessageBox.Show("Client2: " + ex2.Message);
            }
        }
    }
}
